package servlet;

import pwd.DynamicPwd;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by v on 17-5-5.
 */
@WebServlet(name = "Login",value = "/Login")
public class Login extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        Sql sql=Sql.getSql();
        if(sql.release(username,password)){
            //动态生成的一个密码
            String dynamicPwd=DynamicPwd.randomPwd();

            //往cookie里面写入用户名以及动态密码
            Cookie pwd=new Cookie("pwd", dynamicPwd);
            pwd.setPath("/");
            Cookie user=new Cookie("user",username);
            user.setPath("/");
            resp.addCookie(pwd);
            resp.addCookie(user);
            //往服务器里面写入动态密码＋ip组成的字符串
            req.getSession().setAttribute(username,req.getRemoteAddr()+dynamicPwd);
            resp.sendRedirect("home.html");
        }else {
            resp.sendRedirect("/login.html");
        }

    }
}
